package com.lanou.beautifulwardrobe.space;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bartoszlipinski.recyclerviewheader.RecyclerViewHeader;
import com.lanou.beautifulwardrobe.dbHelper.UsersDBHelper;
import com.lanou.beautifulwardrobe.R;
import com.lanou.beautifulwardrobe.space.adapter.SpaceRecyclerViewAdapter;
import com.lanou.beautifulwardrobe.activity.LoginActivity;
import com.lanou.beautifulwardrobe.view.Util;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQAuth;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by dllo on 15/10/26.
 */
public class SpaceFragment extends Fragment implements View.OnClickListener {

    private RecyclerView spaceRecyclerView;
    private SpaceRecyclerViewAdapter adapter;
    private GridLayoutManager manager;
    private RecyclerViewHeader spaceHeader;
    private Button aloginBtn;
    private LinearLayout spaceFail, spaceSuccess;
    private UsersDBHelper helper = UsersDBHelper.getInstance();
    private TextView spaceUser;
    private ImageView spaceImage;

    private static SpaceFragment spaceFragment;


    public static SpaceFragment getspaceFragment() {
        if (spaceFragment == null) {
            spaceFragment = new SpaceFragment();
        }
        return spaceFragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public static String mAppid;

    public void onStart() {
        final Context context = getActivity();
        final Context ctxContext = context.getApplicationContext();
        mAppid = APP_ID;
        mQQAuth = QQAuth.createInstance(mAppid, ctxContext);
        mTencent = Tencent.createInstance(mAppid, getActivity());
        super.onStart();
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.maintab_space_item, null);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        spaceRecyclerView = (RecyclerView) view.findViewById(R.id.spaceRecyclerView);
        spaceHeader = (RecyclerViewHeader) view.findViewById(R.id.spaceHeader);
        aloginBtn = (Button) view.findViewById(R.id.spaceLogin);
        spaceFail = (LinearLayout) view.findViewById(R.id.spaceFail);
        spaceSuccess = (LinearLayout) view.findViewById(R.id.spaceSuccess);
        spaceUser = (TextView) view.findViewById(R.id.spaceUser);
        spaceImage = (ImageView) view.findViewById(R.id.spaceImage);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


        initView();
        initData();
        listener();
    }

    private void initView() {
        adapter = new SpaceRecyclerViewAdapter();
        manager = new GridLayoutManager(getActivity(), 1);
    }

    private void initData() {
        spaceRecyclerView.setLayoutManager(manager);
        spaceRecyclerView.setAdapter(adapter);
        spaceHeader.attachTo(spaceRecyclerView, true);
    }

    private void listener() {
        aloginBtn.setOnClickListener(this);
        spaceImage.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.spaceLogin:
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivityForResult(intent, 200);
                break;
            case R.id.spaceImage:
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("确认退出该用户吗?");
                builder.setIcon(R.mipmap.yk_launcher_desktop_xhdip);
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        spaceFail.setVisibility(View.VISIBLE);
                        spaceSuccess.setVisibility(View.GONE);
                        spaceUser.setText("");
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                builder.show();
                break;
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 300 && requestCode == 200) {
            spaceFail.setVisibility(View.GONE);
            spaceSuccess.setVisibility(View.VISIBLE);
            spaceUser.setText(data.getStringExtra("userName"));
            spaceImage.setImageResource(R.mipmap.taobao_head_23);
            Log.i("lanou", "我进来啦**");


            boolean b = data.getBooleanExtra("qq", false);
            if (b) {
                onClickLogin();
            }
        }
    }

    public static QQAuth mQQAuth;
    private UserInfo mInfo;
    private Tencent mTencent;
    private final String APP_ID = "222222";// 测试时使用，真正发布的时候要换成自己的APP_ID

    private void onClickLogin() {

        if (!mQQAuth.isSessionValid()) {
            IUiListener listener = new BaseUiListener() {

                protected void doComplete(JSONObject values) {
                    updateUserInfo();
                }
            };
            mQQAuth.login(getActivity(), "all", listener);
            // mTencent.loginWithOEM(this, "all",
            // listener,"10000144","10000144","xxxx");
            mTencent.login(getActivity(), "all", listener);
        } else {
            mQQAuth.logout(getActivity());
            updateUserInfo();

        }
    }

    private class BaseUiListener implements IUiListener {


        public void onComplete(Object response) {
//            Util.showResultDialog(getActivity(), response.toString(),
//                    "登录成功");
            doComplete((JSONObject) response);
        }

        protected void doComplete(JSONObject values) {

        }


        public void onError(UiError e) {
            Util.toastMessage(getActivity(), "onError: " + e.errorDetail);
            Util.dismissDialog();
        }

        public void onCancel() {
            Util.toastMessage(getActivity(), "onCancel: ");
            Util.dismissDialog();
        }
    }


    private void updateUserInfo() {
        if (mQQAuth != null && mQQAuth.isSessionValid()) {
            IUiListener listener = new IUiListener() {

                public void onError(UiError e) {
                    // TODO Auto-generated method stub

                }


                public void onComplete(final Object response) {
                    Message msg = new Message();
                    msg.obj = response;
                    msg.what = 0;
                    mHandler.sendMessage(msg);
                    new Thread() {

                        @Override
                        public void run() {
                            JSONObject json = (JSONObject) response;
                            if (json.has("figureurl")) {
                                Bitmap bitmap = null;
                                try {
                                    bitmap = Util.getbitmap(json
                                            .getString("figureurl_qq_2"));
                                } catch (JSONException e) {

                                }
                                Message msg = new Message();
                                msg.obj = bitmap;
                                msg.what = 1;
                                mHandler.sendMessage(msg);
                            }
                        }

                    }.start();
                }


                public void onCancel() {
                }
            };
            mInfo = new UserInfo(getActivity(), mQQAuth.getQQToken());
            mInfo.getUserInfo(listener);

        } else {
            spaceUser.setText("");
            spaceImage.setVisibility(android.view.View.GONE);
            spaceImage.setVisibility(android.view.View.GONE);
        }
    }

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                JSONObject response = (JSONObject) msg.obj;
                if (response.has("nickname")) {
                    try {
                        spaceUser.setVisibility(android.view.View.VISIBLE);
                        spaceUser.setText(response.getString("nickname"));
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            } else if (msg.what == 1) {
                Bitmap bitmap = (Bitmap) msg.obj;
                spaceImage.setImageBitmap(bitmap);
                spaceImage.setVisibility(android.view.View.VISIBLE);
            }
        }

    };
}
